package com.bestcem.xm.wallet.grpc.client.converter;

import com.bestcem.bp.pay.grpc.v1.common.FinanceInfo;
import com.bestcem.bp.pay.grpc.v1.common.ListFinanceResponse;
import com.bestcem.bp.pay.grpc.v1.enums.InvoiceTypeEnum;
import com.bestcem.bp.pay.grpc.v1.services.*;
import com.bestcem.xm.common.core.uitls.GrpcDateUtil;
import com.bestcem.xm.wallet.grpc.client.dto.*;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 钱包相关转换类
 *
 * @author qiongyu.cui <qiongyu.cui@idiaoyan.com>
 * @version v1.0
 * @date 2022/3/18 16:52
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class WalletWalletConverter {

    /**
     * ListFinanceResponse to ListFinanceDTO
     *
     * @param listFinanceResponse 企业钱包交易记录信息
     * @return com.bestcem.xm.user.grpc.client.dto.ListFinanceDTO
     * @author cuiqiongyu <qiongyu.cui@idiaoyan.cn>
     * @date 2022/03/18 17:53
     */
    public static ListFinanceDTO responseToListFinanceDTO(ListFinanceResponse listFinanceResponse) {
        ListFinanceDTO listFinanceDTO = new ListFinanceDTO();
        if (Objects.isNull(listFinanceResponse)) {
            listFinanceDTO.setTotal(0);
            listFinanceDTO.setFinanceRecords(new ArrayList<>());
            return listFinanceDTO;
        }

        listFinanceDTO.setTotal(listFinanceResponse.getTotal());
        List<FinanceDTO> finances = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(listFinanceResponse.getFinanceRecordsList())) {
            for (FinanceInfo financeInfo : listFinanceResponse.getFinanceRecordsList()) {
                FinanceDTO financeDTO = new FinanceDTO();
                financeDTO.setId(financeInfo.getId());
                financeDTO.setBusinessId(financeInfo.getBusinessId());
                financeDTO.setWalletId(financeInfo.getWalletId());
                financeDTO.setType(financeInfo.getTypeValue());
                // 分转成元
                financeDTO.setAmount(BigDecimal.valueOf(financeInfo.getAmount()).movePointLeft(2));
                // 分转成元
                financeDTO.setFee(BigDecimal.valueOf(financeInfo.getFee()).movePointLeft(2));
                // 分转成元
                financeDTO.setBalance(BigDecimal.valueOf(financeInfo.getBalance()).movePointLeft(2));
                financeDTO.setMsg(financeInfo.getMsg());
                // 处理创建时间+8小时问题
                Date date = GrpcDateUtil.getDate(financeInfo.getCreatedAt());
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                calendar.add(Calendar.HOUR_OF_DAY, 8);
                financeDTO.setCreatedAt(calendar.getTime());
                financeDTO.setOpUserId(financeInfo.getOpUserId());
                financeDTO.setOpUserName(financeInfo.getOpUserName());
                financeDTO.setRemark(financeInfo.getRemark());
                finances.add(financeDTO);
            }
        }
        listFinanceDTO.setFinanceRecords(finances);

        return listFinanceDTO;
    }

    /**
     * GetWalletResponse to WalletInfoDTO
     *
     * @param response 钱包信息
     * @return com.bestcem.xm.user.grpc.client.dto.WalletInfoDTO
     * @author panyun <yun.pan@idiaoyan.com>
     * @date 2022/3/20 14:57
     */
    public static WalletInfoDTO responseToWalletInfoDto(GetWalletResponse response) {
        WalletInfoDTO walletInfoDTO = new WalletInfoDTO();
        if (Objects.isNull(response)) {
            return walletInfoDTO;
        }
        walletInfoDTO.setId(response.getWallet().getId())
                .setName(response.getWallet().getName())
                .setBalance(response.getWallet().getBalance());
        return walletInfoDTO;
    }

    /**
     * response to ExpenseInfoDTO
     *
     * @param response 费用信息
     * @return com.bestcem.xm.user.grpc.client.dto.ExpenseInfoDTO
     * @author panyun <yun.pan@idiaoyan.com>
     * @date 2022/3/20 21:24
     */
    public static ExpenseInfoDTO responseToExpenseInfoDTO(GetExpenseResponse response) {
        ExpenseInfoDTO expenseInfoDTO = new ExpenseInfoDTO();
        if (Objects.isNull(response)) {
            return expenseInfoDTO;
        }
        ExpenseInfo expense = response.getExpense();
        expenseInfoDTO.setNotInvoicedAmount(BigDecimal.valueOf(expense.getNotInvoicedAmount()).movePointLeft(2))
                .setInvoicingAmount(BigDecimal.valueOf(expense.getInvoicingAmount()).movePointLeft(2))
                .setInvoicedAmount(BigDecimal.valueOf(expense.getInvoicedAmount()).movePointLeft(2))
                .setRedpacketAmount(BigDecimal.valueOf(expense.getRedpacketAmount()).movePointLeft(2))
                .setSmsAmount(BigDecimal.valueOf(expense.getSmsAmount()).movePointLeft(2))
                .setPurchaseAmount(BigDecimal.valueOf(expense.getPurchaseAmount()).movePointLeft(2));
        return expenseInfoDTO;
    }

    /**
     * response to GetRechargeOrderResponse
     *
     * @param response 订单信息
     * @return com.bestcem.bp.pay.grpc.v1.services.GetRechargeOrderResponse
     * @author panyun <yun.pan@idiaoyan.com>
     * @date 2022/3/20 23:28
     */
    public static RechargeInfoDTO responseToRechargeInfoDto(GetRechargeOrderResponse response) {
        RechargeInfoDTO rechargeInfoDTO = new RechargeInfoDTO();
        if (Objects.isNull(response)) {
            return rechargeInfoDTO;
        }
        RechargeOrder order = response.getOrder();
        rechargeInfoDTO.setId(order.getId())
                .setStatus(order.getStatus().getNumber())
                .setAmount(order.getAmount())
                .setFee(order.getFee())
                .setMsg(order.getMsg());
        return rechargeInfoDTO;
    }

    /**
     * ListInvoicesResponse to ListInvoiceDTO
     *
     * @param listInvoicesResponse 发票结果列表
     * @return com.bestcem.xm.user.grpc.client.dto.ListInvoiceDTO
     * @author cuiqiongyu <qiongyu.cui@idiaoyan.cn>
     * @date 2022/03/19 13:54
     */
    public static ListInvoiceDTO responseToListInvoiceDTO(ListInvoicesResponse listInvoicesResponse) {
        ListInvoiceDTO listInvoiceDTO = new ListInvoiceDTO();
        if (Objects.isNull(listInvoicesResponse)) {
            return listInvoiceDTO;
        }

        listInvoiceDTO.setTotal(listInvoicesResponse.getTotal());
        List<InvoiceDTO> invoices = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(listInvoicesResponse.getInvoiceList())) {
            for (Invoice invoice : listInvoicesResponse.getInvoiceList()) {
                invoices.add(responseToInvoiceDto(invoice));
            }
        }
        listInvoiceDTO.setInvoices(invoices);
        return listInvoiceDTO;
    }

    /**
     * Invoice to InvoiceDTO
     *
     * @param invoice 发票结果列表
     * @return com.bestcem.xm.user.grpc.client.dto.ListInvoiceDTO
     * @author cuiqiongyu <qiongyu.cui@idiaoyan.cn>
     * @date 2022/03/19 13:54
     */
    public static InvoiceDTO responseToInvoiceDto(Invoice invoice) {
        InvoiceDTO invoiceDTO = new InvoiceDTO();
        if (Objects.isNull(invoice)) {
            return invoiceDTO;
        }

        invoiceDTO.setId(invoice.getId());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

        InvoiceDetailDTO detailDTO = new InvoiceDetailDTO();
        detailDTO.setType(invoice.getDetail().getTypeValue());
        // 保留两位小数
        detailDTO.setAmount(BigDecimal.valueOf(invoice.getDetail().getAmount()).setScale(2, RoundingMode.HALF_UP));
        detailDTO.setItin(invoice.getDetail().getItin());
        detailDTO.setTitle(invoice.getDetail().getTitle());
        invoiceDTO.setDetail(detailDTO);

        RecipientDTO recipientDTO = new RecipientDTO();
        recipientDTO.setName(invoice.getRecipient().getName());
        recipientDTO.setDistrictCode(invoice.getRecipient().getDistrictCode());
        recipientDTO.setMobile(invoice.getRecipient().getMobile());
        recipientDTO.setEmail(invoice.getRecipient().getEmail());
        recipientDTO.setAddress(invoice.getRecipient().getAddress());
        invoiceDTO.setRecipient(recipientDTO);

        CompanyDTO companyDTO = new CompanyDTO();
        companyDTO.setTelephone(invoice.getCompany().getTelephone());
        companyDTO.setAddress(invoice.getCompany().getAddress());
        companyDTO.setBankName(invoice.getCompany().getBankName());
        companyDTO.setBankAccount(invoice.getCompany().getBankAccount());
        companyDTO.setLicense(invoice.getCompany().getLicense());
        companyDTO.setTaxCert(invoice.getCompany().getTaxCert());
        invoiceDTO.setCompany(companyDTO);

        invoiceDTO.setStatus(invoice.getStatusValue());
        invoiceDTO.setAuditTime(sdf.format(GrpcDateUtil.getDate(invoice.getAuditTime())));
        invoiceDTO.setExpressNumber(invoice.getExpressNumber());
        invoiceDTO.setRejectReason(invoice.getRejectReason());
        invoiceDTO.setRemark(invoice.getRemark());
        invoiceDTO.setOrgId(invoice.getOrgId());
        invoiceDTO.setDisplayId(invoice.getDisplayId());
        invoiceDTO.setCreateTime(sdf.format(GrpcDateUtil.getDate(invoice.getCreateTime())));
        invoiceDTO.setUpdateTime(sdf.format(GrpcDateUtil.getDate(invoice.getUpdateTime())));
//        invoiceDTO.setWalletId(invoice.getWalletId()); 不返回钱包id给前端

        return invoiceDTO;
    }

    /**
     * 创建发票请求参数转换
     *
     * @param requestDTO 创建发票请求参数
     * @return com.bestcem.bp.pay.grpc.v1.services.CreateInvoiceRequest
     * @author cuiqiongyu <qiongyu.cui@idiaoyan.cn>
     * @date 2022/03/19 15:42
     */
    public static CreateInvoiceRequest requestToCreateInvoiceRequest(ApplyInvoiceRequestDTO requestDTO) {
        CreateInvoiceRequest.Builder builder = CreateInvoiceRequest.newBuilder();
        Invoice.Builder invoiceBuilder = Invoice.newBuilder();
        if (Objects.nonNull(requestDTO)) {
            invoiceBuilder.setOrgId(handleStringValue(requestDTO.getOrgId()));
            invoiceBuilder.setWalletId(handleStringValue(requestDTO.getWalletId()));
            if (Objects.nonNull(requestDTO.getDetail())) {
                InvoiceDetail.Builder invoiceDetailBuilder = InvoiceDetail.newBuilder();
                InvoiceDetailDTO detail = requestDTO.getDetail();
                if (Objects.nonNull(detail.getAmount())) {
                    invoiceDetailBuilder.setAmount(detail.getAmount().floatValue());
                }
                invoiceDetailBuilder.setItin(handleStringValue(detail.getItin()));
                if (Objects.nonNull(detail.getType())) {
                    invoiceDetailBuilder.setType(InvoiceTypeEnum.InvoiceType.forNumber(detail.getType()));
                }
                invoiceDetailBuilder.setTitle(handleStringValue(detail.getTitle()));
                invoiceBuilder.setDetail(invoiceDetailBuilder.build());
            }
            if (Objects.nonNull(requestDTO.getRecipient())) {
                Recipient.Builder recipientBuilder = Recipient.newBuilder();
                RecipientDTO recipient = requestDTO.getRecipient();
                recipientBuilder.setAddress(handleStringValue(recipient.getAddress()));
                recipientBuilder.setDistrictCode(handleStringValue(recipient.getDistrictCode()));
                recipientBuilder.setEmail(handleStringValue(recipient.getEmail()));
                recipientBuilder.setMobile(handleStringValue(recipient.getMobile()));
                recipientBuilder.setName(handleStringValue(recipient.getName()));
                invoiceBuilder.setRecipient(recipientBuilder.build());
            }
            if (Objects.nonNull(requestDTO.getCompany())) {
                Company.Builder companyBuilder = Company.newBuilder();
                CompanyDTO company = requestDTO.getCompany();
                companyBuilder.setAddress(handleStringValue(company.getAddress()));
                companyBuilder.setTaxCert(handleStringValue(company.getTaxCert()));
                companyBuilder.setTelephone(handleStringValue(company.getTelephone()));
                companyBuilder.setBankAccount(handleStringValue(company.getBankAccount()));
                companyBuilder.setBankName(handleStringValue(company.getBankName()));
                companyBuilder.setLicense(handleStringValue(company.getLicense()));
                invoiceBuilder.setCompany(companyBuilder.build());
            }
        }
        builder.setInvoice(invoiceBuilder.build());
        return builder.build();
    }

    /**
     * 获取发票申请列表请求参数转换
     *
     * @param request 获取发票申请列表请求参数
     * @return com.bestcem.bp.pay.grpc.v1.services.ListInvoicesRequest
     * @author cuiqiongyu <qiongyu.cui@idiaoyan.cn>
     * @date 2022/05/09 14:31
     */
    public static ListInvoicesRequest requestToListInvoicesRequest(InvoiceRecordsRequestDTO request) {
        ListInvoicesRequest.Builder builder = ListInvoicesRequest.newBuilder();
        if (Objects.nonNull(request)) {
            builder.setIsAdmin(request.getAdminFlag());
            builder.setIsPage(request.getPageFlag());
            builder.setOrgId(request.getOrgId());
            int page = 1;
            int size = 10;
            builder.setPage(Objects.isNull(request.getPage()) || request.getPage() <= 0 ? page : request.getPage());
            builder.setSize(Objects.isNull(request.getSize()) || request.getSize() <= 0 ? size : request.getSize());
        }
        return builder.build();
    }

    /**
     * 处理string类型
     *
     * @param value 值
     * @return java.lang.String
     * @author cuiqiongyu <qiongyu.cui@idiaoyan.cn>
     * @date 2022/05/23 20:15
     */
    private static String handleStringValue(String value) {
        return Objects.isNull(value) ? "" : value;
    }

}
